package com.jinsilu.freight.ui.activity;

import android.content.Intent;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyActivity;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.DeleteBankInfoApi;
import com.jinsilu.freight.http.request.GetBankCardListApi;
import com.jinsilu.freight.http.response.BankInfoBean;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.adapter.BankListAdapter;
import com.jinsilu.freight.ui.dialog.MenuDialog;
import com.jinsilu.freight.ui.dialog.MessageDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的银行卡管理页面
 *
 * @author yangyang
 * @time 2020-11-10 15:49
 */
public class MyBankManageActivity extends MyActivity {

    private SmartRefreshLayout refresh;
    private RecyclerView recycler;
    private BankListAdapter mAdapter;

    private int pageNumber = 1;

    private final List<String> mDialogDataList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_bank_manage;
    }

    @Override
    protected void initView() {

        refresh = findViewById(R.id.refresh);
        refresh.setEnableLoadMore(false);

        recycler = findViewById(R.id.recycler);

        recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerDecoration.builder(getContext())
                .asSpace().size(10, TypedValue.COMPLEX_UNIT_DIP)
                .showSideDividers()
                .showFirstDivider()
                .showLastDivider()
                .build()
                .addTo(recycler);
        mAdapter = new BankListAdapter(new ArrayList<>());
        mAdapter.addFooterView(getFooter(v -> {
            // 添加银行卡
            startActivityForResult(MyBankAddActivity.class, (resultCode, data) -> {
                // 如果已经添加成功
                if (resultCode == RESULT_OK) {
                    getBankCardList();
                }
            });
        }));
        recycler.setAdapter(mAdapter);
//        mAdapter.setEmptyView(R.layout.layout_empty_data_view);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                BankInfoBean bankInfoBean = (BankInfoBean) adapter.getData().get(position);
//                if (1 == bankInfoBean.getCanOnlinePayment()) { // 屏蔽线上支付
                if (getIntent().hasExtra("load")) {
                    Intent intent = getIntent();
                    intent.putExtra("bankInfo", bankInfoBean);
                    setResult(RESULT_OK, intent);
                    finish();
                }
//                } else {
//                    toast("该银行卡不支持线上支付");
//                }
            }
        });
        mAdapter.addChildClickViewIds(R.id.bank_card_operate);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                BankInfoBean bankInfoBean = (BankInfoBean) adapter.getData().get(position);
                mDialogDataList.clear();

                if (0 != bankInfoBean.getDefaultState()) {
                    mDialogDataList.add("设为默认");
                }
                mDialogDataList.add("删除");

                // 底部选择框
                new MenuDialog.Builder(view.getContext())
                        // 设置 null 表示不显示取消按钮
                        //.setCancel(getString(R.string.common_cancel))
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setList(mDialogDataList)
                        .setListener(new MenuDialog.OnListener<String>() {

                            @Override
                            public void onSelected(BaseDialog dialog, int position, String string) {
                                if (string.equals("删除")) {
                                    new MessageDialog.Builder(dialog.getActivity())
                                            // 标题可以不用填写
                                            .setTitle("")
                                            // 内容必须要填写
                                            .setMessage("是否确认删除？")
                                            // 确定按钮文本
                                            .setConfirm(getString(R.string.common_confirm))
                                            // 设置 null 表示不显示取消按钮
                                            .setCancel(getString(R.string.common_cancel))
                                            // 设置点击按钮后不关闭对话框
                                            //.setAutoDismiss(false)
                                            .setListener(new MessageDialog.OnListener() {

                                                @Override
                                                public void onConfirm(BaseDialog dialog) {
                                                    deleteBankCard(bankInfoBean);
                                                }

                                                @Override
                                                public void onCancel(BaseDialog dialog) {

                                                }
                                            })
                                            .show();
                                } else if (string.equals("设为默认")) {
                                    setDefaultBank(bankInfoBean);
                                }
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {

                            }
                        })
                        .show();
            }
        });

        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNumber += 1;
                getBankCardList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNumber = 1;
                getBankCardList();
            }
        });
    }

    private void setDefaultBank(BankInfoBean bankInfoBean) {
        // 设置为默认银行卡
        EasyHttp.put(this)
                .api(String.format("api/bank/card/default/%s", bankInfoBean.getId()))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> data) {
                        toast(data.getMessage());
                        pageNumber = 1;
                        getBankCardList();
                    }
                });
    }

    private void deleteBankCard(BankInfoBean bankInfoBean) {
        // 删除银行卡
        EasyHttp.delete(this)
                .api(String.format("api/bank/card/%s", bankInfoBean.getId()))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> data) {
                        mAdapter.remove(bankInfoBean);
                    }
                });
    }

    @Override
    protected void initData() {
        getBankCardList();
    }

    private void getBankCardList() {
        // 获取银行信息列表
        EasyHttp.get(this)
                .api(new GetBankCardListApi().setPageNum(String.valueOf(pageNumber)).setPageSize(MTLConstants.PAGE_SIZE))
                .request(new HttpCallback<HttpData<BankInfoBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<BankInfoBean> data) {
                        CommonHelper.finishedLoading(refresh);
                        float total = data.getTotal();
                        refresh.setEnableLoadMore(total / Float.parseFloat(MTLConstants.PAGE_SIZE) > pageNumber);
                        List<BankInfoBean> insuranceNameBeans = data.getRows();
                        if (pageNumber == 1)
                            mAdapter.setList(insuranceNameBeans);
                        else
                            mAdapter.addData(insuranceNameBeans);
                    }
                });
    }

    private View getFooter(View.OnClickListener listener) {
        View footer = LayoutInflater.from(this).inflate(R.layout.footer_of_bank_list, recycler, false);
        footer.setOnClickListener(listener);
        return footer;
    }
}
